#!/usr/bin/env bash

################################################################################
# Runs pylint on changed files using a preconfigured .pylintrc file.
#
# Usage:
#     check/pylint-changed-files [BASE_REVISION]
#
# You can specify a base git revision to compare against (i.e. to use when
# determining whether or not a line is considered to have "changed"). To make
# the tool more consistent, it actually diffs against the most recent common
# ancestor of the specified id and HEAD. So if you choose 'origin/main' you're
# actually diffing against the output of 'git merge-base origin/main HEAD'.
#
# If you don't specify a base revision, the following defaults will be tried,
# in order, until one exists:
#
#     1. upstream/main
#     2. origin/main
#     3. main
#
# If none exists, the script fails.
#
# See check/pylint for linting all files.
################################################################################

# Get the working directory to the repo root.
thisdir=$(dirname "${BASH_SOURCE[0]:?}") || exit $?
repo_dir=$(git -C "${thisdir}" rev-parse --show-toplevel) || exit $?
cd "${repo_dir}" || exit $?

# Figure out which revision to compare against.
if [ -n "$1" ] && [[ $1 != -* ]]; then
    if ! git rev-parse --verify --quiet --no-revs "$1^{commit}"; then
        echo -e "\033[31mNo revision '$1'.\033[0m" >&2
        exit 1
    fi
    rev=$1
elif [ "$(git cat-file -t upstream/main 2> /dev/null)" == "commit" ]; then
    rev=upstream/main
elif [ "$(git cat-file -t origin/main 2> /dev/null)" == "commit" ]; then
    rev=origin/main
elif [ "$(git cat-file -t main 2> /dev/null)" == "commit" ]; then
    rev=main
else
    echo -e "\033[31mNo default revision found to compare against. Argument #1 must be what to diff against (e.g. 'origin/main' or 'HEAD~1').\033[0m" >&2
    exit 1
fi
base=$(git merge-base "${rev}" HEAD)
if [ "$(git rev-parse "${rev}")" == "${base}" ]; then
    echo -e "Comparing against revision '${rev}'." >&2
else
    echo -e "Comparing against revision '${rev}' (merge base ${base})." >&2
    rev="${base}"
fi

typeset -a changed
IFS=$'\n' read -r -d '' -a changed < \
    <(git diff --name-only --diff-filter=d "${rev}" -- \
    "*.py" ":(exclude)cirq-google/cirq_google/cloud/*" ":(exclude)*_pb2.py" \
    | grep -E "^(cirq|dev_tools|examples).*.py$"
)

num_changed=${#changed[@]}

# Run it.
echo "Found ${num_changed} lintable files associated with changes." >&2
if [ "${num_changed}" -eq 0 ]; then
    exit 0
fi
env PYTHONPATH=dev_tools pylint --jobs=0 --rcfile=dev_tools/conf/.pylintrc "${changed[@]}"
